#include <stdlib.h>
#include <stdio.h>
#include "Stack.h"

Stack *createStack(ElemType e) {
    Stack *node = malloc(sizeof *node);
    node->prev = NULL;
    node->next = NULL;
    node->data = e;
    return node;
}

int verificationStack(Stack *stack) {
    return stack == NULL ? 0 : 1;
}

// 初始化栈
Stack *initStack() {
    Stack *head = malloc(sizeof *head);
    head->data = ' ';
    head->prev = NULL;
    head->next = NULL;
    return head;
}

// 压栈
int push(Stack *stack, ElemType e) {
    if (!verificationStack(stack)) {
        return 0;
    }
    // 头指针插入
    Stack *node = createStack(e);
    if (stack->next != NULL) {
        node->next = stack->next;
        stack->next->prev = node;
    }
    stack->next = node;
    return 1;
}

// 弹栈
ElemType pop(Stack *stack) {
    // 判断栈是否为空
    if (!verificationStack(stack) && stack->next == NULL) {
        return 0;
    }
    Stack *node = stack->next;
    stack->next = stack->next->next;
    stack->next->prev = NULL;
    ElemType e = node->data;
    free(node);
    return e;
}

// 获取栈顶元素
ElemType getTop(Stack *stack) {
    // 判断栈是否为空
    if (!verificationStack(stack) && stack->next == NULL) {
        return 0;
    }
    return stack->next->data;
}

// 输出栈
void showStack(Stack *stack) {
    if (!verificationStack(stack)) {
        return;
    }
    printf("[");
    int n = 0;
    Stack *p = stack;
    while (p->next != NULL) {
        p = p->next;
        printf("'%c',", p->data);
        n++;
    }
    printf("]==> 长度 %d\n", n);
}

// 栈长度
int stackLength(Stack *stack) {
    if (!verificationStack(stack)) {
        return 0;
    }
    Stack *p = stack;
    int size = 0;
    while (p->next != NULL) {
        p = p->next;
        size++;
    }
    return size;
}

// 判断栈是否为空
int isEmptyStack(Stack *stack) {
    return !verificationStack(stack) || stack->next == NULL;
}

// 释放内存, 头部删除
void deleteStack(Stack *stack) {
    if (!verificationStack(stack)) {
        return;
    }
    while (stack != NULL) {
        Stack *temp = stack;
        stack = stack->next;
        free(temp);
    }
}

void stackTest() {
    Stack *head = initStack();
    printf("Stack是否为空 %s\n", isEmptyStack(head) == 1 ? "true" : "false");
    printf("Stack长度 %d\n", stackLength(head));
    push(head, 'a');
    push(head, 'b');
    push(head, 'c');
    showStack(head);
    printf("Stack 弹栈元素为：%c\n", pop(head));
    showStack(head);
    printf("Stack 获取栈顶元素为：%c\n", getTop(head));
    printf("Stack长度 %d\n", stackLength(head));
    deleteStack(head);
}